﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace DAL
{
    public class DBHelper
    {
        public static string strCon;
       static DBHelper() {
            strCon = ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;
        }
        /// <summary>
        /// 增删改的通用方法
        /// </summary>
        /// <param name="sql">传入SQL语句</param>
        /// <param name="sprs">参数化</param>
        /// <param name="type">命令执行的类型</param>
        /// <returns>受影响的行数</returns>
        public static int 增删改(string sql,SqlParameter[] sprs,CommandType type)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand(sql,con);
                    cmd.CommandType = type;
                    if (sprs != null)
                        cmd.Parameters.AddRange(sprs);
                    return cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return -1;
            }
        }
        /// <summary>
        /// 白道的通用方法
        /// </summary>
        /// <param name="sql">传入SQL语句</param>
        /// <param name="sprs">参数化</param>
        /// <param name="type">命令执行的类型</param>
        /// <returns>阅读器</returns>
        public static SqlDataReader 白道(string sql,SqlParameter[] sprs,CommandType type)
        {
            try
            {
                SqlConnection con = new SqlConnection(strCon);
                con.Open();
                SqlCommand cmd = new SqlCommand(sql,con);
                cmd.CommandType = type;
                if (sprs != null)
                    cmd.Parameters.AddRange(sprs);
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 单值查询的通用方法
        /// </summary>
        /// <param name="sql">传入SQL语句</param>
        /// <param name="sprs">参数化</param>
        /// <param name="type">命令的执行类型</param>
        /// <returns>单个值</returns>
        public static object 单值(string sql, SqlParameter[] sprs, CommandType type)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand(sql,con);
                    cmd.CommandType = type;
                    if (sprs != null)
                        cmd.Parameters.AddRange(sprs);
                    return cmd.ExecuteScalar();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
